<template>
  <t-modal
    :title="operateType == 1 ? '新增批注' : '编辑批注'"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="handelOk()"
    wrapClassName="add-annotations-container"
    v-bind="footer"
    forceRender
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules">
      <a-form-model-item label="批注名称" prop="name">
        <a-input v-model="form.name" placeholder="请输入批注名称"></a-input>
      </a-form-model-item>
      <a-form-model-item label="批注类型" prop="type">
        <a-select
          v-model="form.type"
          placeholder="请选择批注类型"
          :loading="loading"
        >
          <a-select-option
            :value="item.dicItemCode"
            v-for="item in typeSource"
            :key="item.dicItemCode"
          >
            {{ item.dicItemName }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="参与人员">
        <personnel-popup
          v-model="form.people"
          :disabled="operateType == 2"
          placeholder="请选择参与人员"
          :multiple="true"
          :url="
            '/probusiness/bimMarkMain/getTreeOrganizationAndUserDataByOrgCode?orgCode=' +
              currentProject().orgCode
          "
        ></personnel-popup>
      </a-form-model-item>
      <a-form-model-item label="批注描述">
        <a-input
          type="textarea"
          :rows="4"
          v-model="form.desc"
          placeholder="请输入批注描述"
        ></a-input>
      </a-form-model-item>
      <a-form-model-item label="批注图片">
        <div class="upload-img">
          <div
            class="upload-button"
            @click="addAnnotationsImg()"
            v-if="operateType == 1"
          >
            <a-icon type="plus" />
            <div class="ant-upload-text">
              上传
            </div>
          </div>
          <div
            class="file-list"
            v-for="(item, index) in form.files"
            :key="index"
          >
            <img :src="item" @click="previewImg(item)" title="点击预览" />
            <!-- 删除按钮 -->
            <div
              class="delete-button"
              @click="deleteImg(item, index)"
              v-if="operateType == 1"
            >
              <a-icon
                type="close"
                :style="{
                  fontSize: '12px',
                  color: '#ffffff',
                }"
              />
            </div>
          </div>
        </div>
      </a-form-model-item>
    </a-form-model>
    <!-- 图片预览弹窗 -->
    <previewImage
      :imgSrc="imgPreview"
      :visible.sync="imgVisible"
    ></previewImage>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { PersonnelPopup } from "@/components";
import previewImage from "@/components/TopVUI/custom/previewImage";
import { getDicItemByCode } from "@/api/common.js";
export default {
  inject: ["currentProject", "fabricCanvas", "sceneSource"],
  components: {
    PersonnelPopup,
    previewImage,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    reOpen: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: "1",
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
    footer: {
      type: Object,
      default() {
        return {};
      },
    },
    snapshot: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      form: {
        name: "",
        type: undefined,
        people: "",
        desc: "",
        files: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入批注名称",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择批注类型",
          },
        ],
      },
      fileList: [],
      //图片预览弹窗
      imgVisible: false,
      imgPreview: "",
      //批注类型
      typeSource: [],
      loading: false,
    };
  },

  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getTypeData();
          let { operateType } = this;
          //编辑
          if (operateType == 2) {
            let {
              commentName,
              commentDesc,
              commentType,
              creatorId,
              bimCommentImages,
            } = this.parameter;
            this.form.name = commentName;
            this.form.type = commentType;
            this.form.desc = commentDesc;
            this.form.people = creatorId;
            this.form.files = bimCommentImages;
          } else {
            Promise.all([this.getBimSnapshot(), this.getSnapshot()]).then(
              (result) => {
                this.combineImages(result[0], result[1], (combinedImage) => {
                  if (operateType == 1) {
                    this.form.files.push(combinedImage);
                  }
                });
              }
            );
          }
        }
      },
      immediate: true,
    },
  },

  methods: {
    //查询批注类型
    getTypeData() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        getDicItemByCode({ code: "commentType" })
          .then((res) => {
            let { data } = res;
            this.typeSource = data ?? [];
            resolve();
          })
          .catch((_) => {
            this.typeSource = [];
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //新增批注图片
    addAnnotationsImg() {
      this.$emit("update:visible", false);
      this.$emit("update:reOpen", true);
      this.$emit("update:operateType", this.operateType);
    },

    //预览
    previewImg(data) {
      this.imgPreview = data;
      this.imgVisible = true;
    },

    //删除图片
    deleteImg(file, index) {
      this.form.files = this.form.files.filter((v, i) => i != index);
    },

    //监听文件选择
    beforeUpload(file) {
      let filereader = new FileReader();
      filereader.onload = (e) => {
        let src = e.target.result;
        this.form.files.push(src);
      };
      filereader.readAsDataURL(file);
      return false;
    },

    //表单提交
    handelOk() {
      let { operateType } = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          switch (operateType) {
            //新增
            case 1:
              this.addSave();
              break;

            //编辑
            case 2:
              this.editSave();
              break;

            default:
              break;
          }
        }
      });
    },

    //新增保存
    addSave() {
      let { sceneId } = this.sceneSource();
      let { orgCode, foreignUuid } = this.currentProject();
      let { name, type, people, desc, files } = this.form;
      let { camDir, camPos, camRotate } = BlackHole3D.Camera.getCamLocate();
      axios
        .post(
          "/probusiness/bimCommentMain/save",
          {
            sceneId,
            proCode: orgCode,
            projid: foreignUuid,
            commentName: name,
            commentDesc: desc,
            commentType: type,
            camRotate: JSON.stringify(camRotate),
            camPos: JSON.stringify(camPos),
            camDir: JSON.stringify(camDir),
            bimCommentUserIds: people.split(","),
            bimCommentImages: files,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { statusCode } = res;
          if (statusCode == 200) {
            this.$message.success(`新增成功！`);
            this.$emit("refresh", { event: "add" });
            this.closeModal();
          } else {
            this.$message.error(`新增失败，请稍后重试！`);
          }
        })
        .finally((_) => {
          this.submitLoading = false;
        });
    },

    //编辑
    editSave() {
      let { sceneId } = this.sceneSource();
      let { uuid, camDir, camPos, camRotate } = this.parameter;
      let { orgCode, foreignUuid } = this.currentProject();
      let { name, type, people, desc, files } = this.form;
      axios
        .post(
          "/probusiness/bimCommentMain/update",
          {
            uuid,
            sceneId,
            proCode: orgCode,
            projid: foreignUuid,
            commentName: name,
            commentDesc: desc,
            commentType: type,
            camRotate: camRotate,
            camPos: camPos,
            camDir: camDir,
            bimCommentUserIds: people.split(","),
            bimCommentImages: files,
          },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          let { statusCode } = res;
          if (statusCode == 200) {
            this.$message.success(`编辑成功！`);
            this.$emit("refresh", { event: "edit" });
            this.closeModal();
          } else {
            this.$message.error(`编辑失败，请稍后重试！`);
          }
        })
        .finally((_) => {
          this.reChooseFlag = false;
          this.submitLoading = false;
        });
    },

    //重置表单
    resetForm() {
      this.form = {
        name: "",
        type: undefined,
        people: "",
        desc: "",
        files: [],
      };
      this.fileList = [];
      this.$refs.ruleForm.resetFields();
    },

    //获取bim快照
    getBimSnapshot() {
      return new Promise((resolve, reject) => {
        const canvas = document.getElementById("blackHoleCanvas");
        if (canvas) {
          const context = canvas.getContext("2d");
          const dataUrl = canvas.toDataURL();
          resolve(dataUrl);
        } else {
          resolve("");
        }
      });
    },

    //获取快照
    getSnapshot() {
      return new Promise((resolve, reject) => {
        let canvas = this.fabricCanvas();
        if (canvas) {
          let imageData = canvas.toDataURL({
            format: "png",
            quality: 1,
            enableRetinaScaling: true,
          });
          resolve(imageData);
        } else {
          resolve("");
        }
      });
    },

    //图片合并
    combineImages(image1, image2, callback) {
      // 创建一个canvas元素
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      // 加载两张图片
      let img1 = new Image();
      img1.src = image1;
      let img2 = new Image();
      img2.src = image2;
      // 确保图片加载完成后再合成
      img1.onload = function() {
        canvas.width = img1.width;
        canvas.height = img1.height;
        ctx.drawImage(img1, 0, 0); // 绘制第一张图片
        ctx.drawImage(img2, 0, 0); // 绘制第二张图片
        // 回调函数返回合成后的图片dataURL
        callback(canvas.toDataURL("image/png"));
      };
    },

    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-annotations-container {
  .upload-img {
    display: flex;
    flex-wrap: wrap;
    .upload-button {
      display: flex;
      width: 110px;
      height: 110px;
      border-radius: 6px;
      background: #fafafa;
      border: 1px dashed #d9d9d9;
      cursor: pointer;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
      flex-direction: column;
      .anticon-plus {
        font-size: 26px;
      }
    }
    .file-list {
      width: 110px;
      height: 110px;
      background: #fafafa;
      border-radius: 6px 6px 6px 6px;
      border: 1px solid #d9d9d9;
      margin: 0 8px 8px 0;
      position: relative;
      img {
        cursor: pointer;
        height: 100%;
        width: 100%;
        object-fit: contain;
      }
      .delete-button {
        position: absolute;
        width: 24px;
        height: 20px;
        background: #ff2d2d;
        border-radius: 0px 6px 0px 20px;
        opacity: 0.6;
        top: 0;
        right: 0;
        cursor: pointer;
        z-index: 99;
        .anticon-close {
          position: relative;
          top: -10px;
          right: -8px;
          font-size: 12px;
          color: #ffffff;
        }
      }
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 100px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
}
</style>
